use std::collections::BTreeMap;

#[derive(Debug)]
pub enum Node {
	Class(Module),
	Module(Module),
}
#[derive(Debug, Default)]
pub struct Module(BTreeMap<String, Node>);
impl Module {
	pub fn push(&mut self, path: &mut Vec<String>) {
		let name = path.remove(0);
		if path.is_empty() {
			self.0.insert(name, Node::Class(Module(BTreeMap::new())));
		} else {
			let node = self.0.entry(name).or_insert(Node::Module(Module(BTreeMap::new())));
			match node {
				Node::Class(v) => v.push(path),
				Node::Module(v) => v.push(path),
			}
		}
	}
}

impl std::fmt::Display for Module {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		for (name, node) in self.0.iter() {
			match node {
				Node::Class(_) => f.write_fmt(format_args!(
					r##"
mod {0};
pub use {0}::*;
"##,
					name.replace("$", "")
				))?,
				Node::Module(m) => f.write_fmt(format_args!(
					r##"
pub mod {0} {{
	{1}
}}
"##,
					name, m
				))?,
			}
		}
		Ok(())
	}
}
